package com.zk;

import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/15  14:03
 * 描述:
 */
public class ZkApplication {

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        MyWatcher myWatcher = new MyWatcher();

        ZooKeeper zooKeeper=new ZooKeeper("127.0.0.1:2181",30000,myWatcher);
        //1、创建一个持久节点
        //zooKeeper.create("/TESTTT","data of node".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

        //给/TESTTT1节点注册一个监控
        //zooKeeper.getChildren("/TESTTT",true);

        //给/TESTTT2节点注册一个监控
        //zooKeeper.exists("/TESTTT2",new MyWatcher2());

        //zooKeeper.create("/TESTTT2","yy".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);

        //获取节点的数据
        Stat stat=new Stat();
        //在获取数据的时候可以添加监控
        /*byte[] data = zooKeeper.getData("/TESTTT2", new MyWatcher2(), stat);
        String s = new String(data);
        System.out.println(s+"---------"+JSON.toJSONString(stat));*/

        //修改节点的数据
        /*Stat stat1 = zooKeeper.setData("/TESTTT2", "TTTTT".getBytes(), stat.getVersion());
        System.out.println(s+"========="+JSON.toJSONString(stat1));
        Stat stat2=new Stat();
        zooKeeper.getData("/TESTTT2", new MyWatcher2(), stat2);
        System.out.println("===========");*/

        //
        //Transaction transaction = zooKeeper.transaction();
        //System.out.println(JSON.toJSONString(transaction));
        //zooKeeper.delete("/TESTTT2",stat2.getVersion());

        //对子目录的操作
        //zooKeeper.create("/TESTTT3","yy".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        //zooKeeper.create("/TESTTT3/T","uuuu".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT_SEQUENTIAL);

        List<String> children = zooKeeper.getChildren("/TESTTT3", new MyWatcher2());

        children.forEach((str)->{
            System.out.println(str);
            try {
                byte[] data = zooKeeper.getData("/TESTTT3/" + str, true, null);
                System.out.println(new String(data));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //子节点发生改变
        zooKeeper.create("/TESTTT3/T","uuuu".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT_SEQUENTIAL);


        zooKeeper.close();

        

    }

}
